import CryptoJS from 'crypto-js';

const tool = {};

/**
 * window.localStorage 浏览器永久缓存
 * @method set 设置永久缓存
 * @method get 获取永久缓存
 * @method remove 移除永久缓存
 * @method clear 移除全部永久缓存
 */
tool.local = {
  set(table, settings) {
    // return window.localStorage.setItem(table, JSON.stringify(settings));
    return localStorage.setItem(table, JSON.stringify(settings));
  },
  get(table) {
    let data = localStorage.getItem(table);
    try {
      data = JSON.parse(data);
    } catch (err) {
      return null;
    }
    return data;
  },
  remove(table) {
    return localStorage.removeItem(table);
  },
  clear() {
    return localStorage.clear();
  },
};

/**
 * window.sessionStorage 浏览器临时缓存
 * @method set 设置临时缓存
 * @method get 获取临时缓存
 * @method remove 移除临时缓存
 * @method clear 移除全部临时缓存
 */
tool.session = {
  set(table, settings) {
    return sessionStorage.setItem(table, JSON.stringify(settings));
  },
  get(table) {
    let data = sessionStorage.getItem(table);
    try {
      data = JSON.parse(data);
    } catch (err) {
      return null;
    }
    return data;
  },
  remove(table) {
    return sessionStorage.removeItem(table);
  },
  clear() {
    return sessionStorage.clear();
  },
};

/**
 * CookieStorage
 */
tool.cookie = {
  set(name, value, config = {}) {
    var cfg = {
      expires: null,
      path: null,
      domain: null,
      secure: false,
      httpOnly: false,
      ...config
    };
    var cookieStr = `${name}=${escape(value)}`;
    if (cfg.expires) {
      var exp = new Date();
      exp.setTime(exp.getTime() + parseInt(cfg.expires) * 1000);
      cookieStr += `;expires=${exp.toGMTString()}`;
    }
    if (cfg.path) {
      cookieStr += `;path=${cfg.path}`;
    }
    if (cfg.domain) {
      cookieStr += `;domain=${cfg.domain}`;
    }
    document.cookie = cookieStr;
  },
  get(name) {
    var arr = document.cookie.match(new RegExp("(^| )" + name + "=([^;]*)(;|$)"));
    if (arr != null) {
      return unescape(arr[2]);
    } else {
      return null;
    }
  },
  remove(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    document.cookie = `${name}=;expires=${exp.toGMTString()}`;
  },
};

/**
 * Fullscreen
 * @param element
 */
tool.screen = (element) => {
  let isFull = !!(document.webkitIsFullScreen || document.mozFullScreen || document.msFullscreenElement || document.fullscreenElement);
  if (isFull) {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.msExitFullscreen) {
      document.msExitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitExitFullscreen) {
      document.webkitExitFullscreen();
    }
  } else {
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen();
    }
  }
};

/**
 * 复制对象
 */
tool.objCopy = (obj) => {
  if (obj === undefined) {
    return undefined
  }
  return JSON.parse(JSON.stringify(obj));
};

/**
 * 生成唯一ID
 */
tool.generateId = function() {
  return Math.floor(Math.random() * 100000 + Math.random() * 20000 + Math.random() * 5000)
};

/**
 * 日期格式化
 */
tool.dateFormat = (date, fmt = 'yyyy-MM-dd hh:mm:ss', isDefault = '-') => {
  if (date.toString().length == 10) {
    date = date * 1000;
  }
  date = new Date(date);
  if (date.valueOf() < 1) {
    return isDefault;
  }
  let o = {
    'M+': date.getMonth() + 1, // 月份
    'd+': date.getDate(), // 日
    'h+': date.getHours(), // 小时
    'm+': date.getMinutes(), // 分
    's+': date.getSeconds(), // 秒
    'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
    'S': date.getMilliseconds(), // 毫秒
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
    }
  }
  return fmt;
}

/**
 * 转Unix时间戳
 */
tool.toUnixTime = (date) => {
  return Math.floor((new Date(date)).getTime() / 1000);
};

/**
 * 千分符
 */
tool.groupSeparator = (num) => {
  num = num + '';
  if (!num.includes('.')) {
    num += '.';
  }
  return num.replace(/(\d)(?=(\d{3})+\.)/g, function ($0, $1) {
    return $1 + ',';
  }).replace(/\.$/, '');
};

tool.md5 = (str) => {
  return CryptoJS.MD5(str).toString();
};

tool.base64 = {
  encode(data) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data));
  },
  decode(cipher) {
    return CryptoJS.enc.Base64.parse(cipher).toString(CryptoJS.enc.Utf8);
  },
};

tool.aes = {
  encode(data, secretKey) {
    const result = CryptoJS.AES.encrypt(data, CryptoJS.enc.Utf8.parse(secretKey), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return result.toString();
  },
  decode(cipher, secretKey) {
    const result = CryptoJS.AES.decrypt(cipher, CryptoJS.enc.Utf8.parse(secretKey), {
      mode: CryptoJS.mode.ECB,
      padding: CryptoJS.pad.Pkcs7,
    });
    return CryptoJS.enc.Utf8.stringify(result);
  },
};

tool.formatSize = (size) => {
  if (typeof size == 'undefined') {
    return '0';
  }
  let units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
  let index = 0;
  for (let i = 0; size >= 1024 && i < 5; i++) {
    size /= 1024;
    index = i;
  }
  return Math.round(size, 2) + units[index];
}

/**
 * 对象转url参数
 * @param data
 * @param isPrefix
 * @returns {string|string}
 */
tool.httpBuild = (data, isPrefix = false) => {
  let prefix = isPrefix ? '?' : '';
  let _result = [];
  for (let key in data) {
    let value = data[key];
    // 去掉为空的参数
    if (['', undefined, null].includes(value)) {
      continue;
    }
    if (value.constructor === Array) {
      value.forEach(_value => {
        _result.push(encodeURIComponent(key) + '[]=' + encodeURIComponent(_value));
      })
    } else {
      _result.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
    }
  }

  return _result.length ? prefix + _result.join('&') : '';
};

tool.getRequestParams = (url) => {
  const theRequest = new Object();
  if (url.indexOf('?') !== -1) {
    const params = url.split('?')[1].split('&');
    for (let i = 0; i < params.length; i++) {
      const param = params[i].split('=');
      theRequest[param[0]] = decodeURIComponent(param[1]);
    }
  }
  return theRequest;
};

// 美化打印实现方法
tool.prettyLog = (title, info, color = '#3488ff') => {
  console.log(
    `%c ${title} %c ${info} %c`,
    `background: ${color}; border: 1px solid ${color}; padding: 1px; border-radius: 2px 0 0 2px; color: #fff;`,
    `border: 1px solid ${color}; padding: 1px; border-radius: 0 2px 2px 0; color: ${color};`,
    'background:transparent'
  );
}

export default tool;
